package cn.com.taiji.pos.controller;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.common.util.MD5;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/BeginWork")
public class BeginWorkController {
    @Autowired
    private ISystemAclUserService systemAclUserService;
    @Autowired
    private ISystemPosMachineService systemPosMachineService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private IFrontToWorkService frontToWorkService;
    @Autowired
    private IConfigCauseService configCauseService;
    @Autowired
    private IConfigBusinessTypeService configBusinessTypeService;
    @Autowired
    private ISystemAclEmpowerstrikeService systemAclEmpowerstrikeService;
    @Value("${RETURN_AUTHORITY_ID}")
    private String RETURN_AUTHORITY_ID;

    /**
     * 开班登录
     *
     * @param request
     * @param response
     * @param loginUser
     */
    @RequestMapping("/login")
    public String beginWork(Model model, SystemAclUser loginUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
        model.addAttribute("result", "fail");
        if (!StringUtils.hasText(loginUser.getLoginName())) {
            model.addAttribute("message", "用户名为空");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        if (!StringUtils.hasText(loginUser.getPassword())) {
            model.addAttribute("message", "密码为空");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        SystemAclUser user = systemAclUserService.findByLoginName(loginUser.getLoginName());
        if (user == null) {
            model.addAttribute("message", "用户名不存在");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else if (!MD5.MD5Encode(loginUser.getPassword()).equals(user.getPassword())) {
            if (systemAclUserService.findByLoginNameAndPassword(loginUser) == null) {
                model.addAttribute("message", "密码不正确");
                return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
            }
        }
        FrontToWork frontToWork = new FrontToWork();
        frontToWork.setReserveAmount(loginUser.getReserveAmount());//备用金额
        frontToWork.setConfirmAmount(loginUser.getConfirmAmount());//确认金额
        if (!loginUser.getReserveAmount().equals(loginUser.getConfirmAmount()) && !StringUtils.hasText(loginUser.getReason())) {
            model.addAttribute("message", "备用金额与确认金额不一致");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        frontToWork.setReasonId(loginUser.getReason());
        SystemPosMachine systemPosMachine = systemPosMachineService.findByPhysicalCode(loginUser.getPhysicalCode());
        if (systemPosMachine != null) {
            frontToWork.setPosMachineId(systemPosMachine.getId());//POS机物理标识
            frontToWork.setRestaurantId(systemPosMachine.getRestaurantId());//餐厅
            if (StringUtils.hasText(loginUser.getReserveAmount() + "")) {
                systemPosMachine.setMoney(loginUser.getReserveAmount());
            } else {
                systemPosMachine.setMoney(BigDecimal.ZERO);
            }
            systemPosMachineService.updateById(systemPosMachine);
        } else {
            model.addAttribute("message", "未查询到该POS机");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
        QueryWrapper<ConfigMealTime> configMealTimeWrapper = new QueryWrapper<>();
        configMealTimeWrapper.le("START_TIME", df.format(LocalTime.now()));
        configMealTimeWrapper.ge("END_TIME", df.format(LocalTime.now()));
        ConfigMealTime configMealTime = configMealTimeService.getOne(configMealTimeWrapper, false);
        if (configMealTime != null) {
            frontToWork.setMealTimeId(configMealTime.getId());//餐次
        }
        frontToWork.setCreatorId(user.getId());
        frontToWork.setCashierId(user.getId());
        frontToWork.setCreatorName(user.getName());
        frontToWork.setCreateTime(LocalDateTime.now());
        frontToWorkService.save(frontToWork);
        //查询权限
        SystemAclEmpowerstrike systemAclEmpowerstrike = systemAclEmpowerstrikeService.findByUser(user.getId());
        if (systemAclEmpowerstrike != null && ("BOTH".equals(systemAclEmpowerstrike.getType()) || "CONSUMERSTRIKE".equals(systemAclEmpowerstrike.getType()))) {
            user.setCzAuthority(true);
        }
        user.setTkAuthority(systemAclUserService.hasAuthority(RETURN_AUTHORITY_ID, user.getId()));
        //查询pos机业务类型
        List<ConfigBusinessType> configBusinessTypeList = configBusinessTypeService.getListForType(loginUser.getPhysicalCode());
        List<String> idList = configBusinessTypeList.stream().map(ConfigBusinessType::getId).collect(Collectors.toList());
        user.setPw(loginUser.getPassword());
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, user);
        WebUtils.setSessionAttribute(request, "configBusinessTypeList", idList);
        model.addAttribute("result", "success");
        model.addAttribute("message", "开班成功");
        model.addAttribute("systemPosMachine", systemPosMachine);
        model.addAttribute("configMealTime", configMealTime);
        model.addAttribute("user", user);
//        response
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 操作原因(交班,接班,冲账等)
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/Reason", method = RequestMethod.POST)
    public String handoverReason(Model model, HttpServletRequest request, HttpServletResponse response) {
        List<ConfigCause> reasonList = configCauseService.query().orderByAsc("SORT_NO").list();
        model.addAttribute("result", "success");
        model.addAttribute("reasonList", reasonList);
        return JSONObject.toJSONString(model);
    }

    /**
     * 查询pos机金额
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "posMachineMoney", method = RequestMethod.POST)
    public String posMachineMoney(Model model, HttpServletRequest request, HttpServletResponse response) {
        String physicalCode = request.getParameter("physicalCode");
        SystemPosMachine systemPosMachine = systemPosMachineService.findByPhysicalCode(physicalCode);
        if (systemPosMachine != null) {
            model.addAttribute("money", systemPosMachine.getMoney());
        } else {
            model.addAttribute("money", 0);
        }

        return JSONObject.toJSONString(model);
    }

}
